<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>不刷新页面更新url参数</title>
  </head>
  <body>
    <button id="replaceUrl">更改url</button>
  </body>
  <script>
    const replaceUrlDom = document.getElementById('replaceUrl')

    const objToParams = (params) => {
        return Object.keys(params).reduce((str, item, index) => {
        if (index !== 0) str += '&'
        str += `${item}=${params[item]}`
        return str
      }, '')
    }
    const replaceUrl = () => {
      const oldParams = new URLSearchParams(window.location.search)
      const params = {
        ...oldParams,
        pageNum: 1 + Math.floor(Math.random() * 10),
        pageSize: 20 + Math.floor(Math.random() * 20),
      }
      const param = objToParams(params)
      history.replaceState(
        { pageNum: 1, pageSize: 20 },
        '',
        `${window.location.origin}${window.location.pathname}?${param}`
      )
    }
    replaceUrlDom.onclick = replaceUrl
  </script>
</html>
